package com.ruicar.afs.cloud.apply.pre.loan.mq.receiver;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.apply.business.condition.WorkflowAgencyTaskCondition;
import com.ruicar.afs.cloud.apply.business.mq.config.ArchiveConfig;
import com.ruicar.afs.cloud.apply.business.service.ApplyRecordDetailsService;
import com.ruicar.afs.cloud.apply.business.service.ArchiveMQService;
import com.ruicar.afs.cloud.apply.business.service.WorkflowAgencyTaskService;
import com.ruicar.afs.cloud.apply.common.entity.*;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.contract.mapper.LoanGpsRuleInfoMapper;
import com.ruicar.afs.cloud.apply.contract.mapper.LoanModeRuleInfoMapper;
import com.ruicar.afs.cloud.apply.contract.service.ApplyReturnRecordService;
import com.ruicar.afs.cloud.apply.contract.service.impl.ApplyContractInfoServiceImpl;
import com.ruicar.afs.cloud.apply.pre.loan.service.*;
import com.ruicar.afs.cloud.apply.pre.loan.service.impl.ApplyOrderInfoServiceImpl;
import com.ruicar.afs.cloud.bizcommon.dto.rules.atom.AfsRuleInfoDto;
import com.ruicar.afs.cloud.bizcommon.rules.entity.*;
import com.ruicar.afs.cloud.bizcommon.rules.mapper.*;
import com.ruicar.afs.cloud.bizcommon.rules.service.AfsRuleInfoService;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.ApplyStatusEnum;
import com.ruicar.afs.cloud.common.modules.dto.mq.approve.*;
import com.ruicar.afs.cloud.common.modules.dto.mq.loan.AttachmentDTO;
import com.ruicar.afs.cloud.common.modules.dto.mq.loan.SendToApplyContractInfoDTO;
import com.ruicar.afs.cloud.common.modules.dto.mq.loan.gpsdto.LoanGpsRuleDTO;
import com.ruicar.afs.cloud.common.modules.dto.mq.loan.loanmodeldto.LoanModelRuleDto;
import com.ruicar.afs.cloud.common.mq.rabbit.listener.AfsMqBizProcessor;
import com.ruicar.afs.cloud.common.mq.rabbit.message.MqTransCode;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import com.ruicar.afs.cloud.parameter.commom.enums.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 审批MQ接收处理
 *
 * @author 耿继辉
 */
@AllArgsConstructor
@Slf4j
@Component
@ConditionalOnProperty(prefix = "com.ruicar.afs.cloud.mq.rabbit", name = "enable")
public class ApplyApproveDealProcessor implements AfsMqBizProcessor<ApproveSubmitInfo> {
    private final ApplyRecordDetailsService applyRecordDetailsService;
    private final ApplyOprRecordService applyOprRecordService;
    private final ApplyOrderInfoServiceImpl applyOrderInfoService;
    private final ApplyRemindDetailsService applyRemindDetailsService;
    private final ApplyReturnRecordService applyReturnRecordService;
    private final ApplyContractInfoServiceImpl applyContractInfoService;
    private final ApplyCustBaseInfoService applyCustBaseInfoService;
    private final ComAttachmentFileService comAttachmentFileService;
    private final LoanGpsRuleInfoMapper loanGpsRuleInfoMapper;
    private final AfsRuleTransExpressMapper ruleTransExpressMapper;
    private final AfsRuleResultMappingMapper afsRuleResultMappingMapper;
    private final AfsRuleItemMapper ruleItemMapper;
    private final AfsRuleInputMappingMapper mappingMapper;
    private final AfsRuleExpressAtomMapper ruleExpressAtomMapper;
    private final AfsRuleExpressMapper ruleExpressMapper;
    private final AfsRuleInfoService afsRuleInfoService;
    private final WorkflowAgencyTaskService workflowAgencyTaskService;
    private final ApplyConditionApprovalService applyConditionApprovalService;
    private final LoanModeRuleInfoMapper loanModeRuleInfoMapper;
    private final ArchiveMQService archiveMQService;
    private final ApplyOrderInfoService orderInfoService;

    /**
     * @param entity afs trans entity
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean processMessage(ApproveSubmitInfo entity) throws Exception {
        //根据返回报文，更新进件订单管理的订单状态
        if (entity.getApplyResultInfoDto() != null) {
            if (entity.getApplyResultInfoDto().getResult().equals(ResultBooleanEnum.TRUE.getCode())) {
                //入库成功,更新状态
                this.successMessage(entity.getApplyResultInfoDto());
            } else if (entity.getApplyResultInfoDto().getResult().equals(ResultBooleanEnum.FALSE.getCode())) {
                //入库失败，更新状态
                this.failedMessage(entity.getApplyResultInfoDto());
            }
        }
        if (entity.getApproveInformDto() != null) {
            //审批报文解析
            this.applyRecordDetails(entity.getApproveInformDto());
        } else if (entity.getLeaveMessageDto() != null) {
            //留言报文解析
            this.applyRemindDetails(entity.getLeaveMessageDto());
        } else if (entity.getConditionalApprovalDto() != null) {
            //附条件核准报文解析
            this.applyConditionApptoval(entity.getConditionalApprovalDto());
        } else if (entity.getSendToApplyContractInfoDTO() != null) {
            //解析退回合作商参数
            this.applyBackToPartner(entity.getSendToApplyContractInfoDTO());
        } else if (entity.getLoanGpsRuleDTO() != null) {
            this.applyLoanGpsRuleInfo(entity.getLoanGpsRuleDTO());
        } else if (entity.getLoanModelRuleDto() != null) {
            this.applyLoanModelRuleInfo(entity.getLoanModelRuleDto());
        } else if (entity.getApplyNoList() != null) {
            this.applyLoanCancel(entity.getApplyNoList());
        }
        return true;
    }

    /**
     * @return
     */
    @Override
    public MqTransCode getCode() {
        return MqTransCode.AFS_POS_APPLY_CASE_CTM_MODIFY_ORDER;
    }

    /**
     * Re queue on fail boolean
     * 消费失败是否返回队列 默认不返回
     *
     * @return the boolean
     */
    @Override
    public boolean reQueueOnFail() {
        return false;
    }

    /**
     * 返回成功，更新状态
     *
     * @param entity
     */
    public void successMessage(ApplyResultInfoDto entity) {
        log.info("--申请编号:" + entity.getApplyNo() + ",信审接收报文成功");
    }

    /**
     * @param entity
     */
    public void failedMessage(ApplyResultInfoDto entity) {
        //查询当前订单状态
        ApplyOrderInfo orderInfoByApplyNo = applyOrderInfoService.getOrderInfoByApplyNo(entity.getApplyNo());
        if (ApplyConstants.APPLY_STATUS_REPLY.equals(orderInfoByApplyNo.getApplyStatus())) {
            //查询操作记录-复议
            ApplyOprRecord applyOprRecord = this.applyOprRecordService.getOne(Wrappers.<ApplyOprRecord>query().lambda().eq(ApplyOprRecord::getApplyNo, entity.getApplyNo())
                    .eq(ApplyOprRecord::getApplyType, String.valueOf(OrderOprType.RECONSIDER)));
            if (ObjectUtil.isNotNull(applyOprRecord)) {
                //重新把复议退回待办任务激活
                WorkflowAgencyTaskCondition workflowAgencyTaskCondition = new WorkflowAgencyTaskCondition();
                workflowAgencyTaskCondition.setBusinessNo(entity.getApplyNo());
                workflowAgencyTaskCondition.setBusinessType(String.valueOf(OrderOprType.RECONSIDER));
                workflowAgencyTaskService.reActiveWorkflow(workflowAgencyTaskCondition);
            } else {
                //重新把常规退回待办任务激活
                WorkflowAgencyTaskCondition workflowAgencyTaskCondition = new WorkflowAgencyTaskCondition();
                workflowAgencyTaskCondition.setBusinessNo(entity.getApplyNo());
                workflowAgencyTaskCondition.setBusinessType(String.valueOf(OrderOprType.NORMAL));
                workflowAgencyTaskService.reActiveWorkflow(workflowAgencyTaskCondition);
            }
            //状态重置为修订回复
            this.applyOrderInfoService.updateApplyStatus(entity.getApplyNo(), ApplyConstants.APPLY_STATUS_SUSPEND);
        } else {
            //更新进件订单状态,失败为草稿状态
            this.applyOrderInfoService.updateApplyStatus(entity.getApplyNo(), ApplyConstants.APPLY_STATUS_DRAFT);
        }
        log.info("--申请编号:" + entity.getApplyNo() + "，信审接收失败报文");
    }

    /**
     * 解析审批记录报文,保存数据,更新进件订单表的订单状态
     *
     * @param approveInfoDto
     */
    public void applyRecordDetails(ApproveInformDto approveInfoDto) {
        ApplyCustBaseInfo mainCustBaseInfo = this.applyCustBaseInfoService.getCustBaseInfo(approveInfoDto.getApplyNo(), ApplyConstants.PRINCIPAL_BORROWER);
        ApplyOrderInfo orderInfoByApplyNo = applyOrderInfoService.getOrderInfoByApplyNo(approveInfoDto.getApplyNo());
        ApplyOprRecord applyOprRecord = this.applyOprRecordService.getOne(Wrappers.<ApplyOprRecord>query().lambda().eq(ApplyOprRecord::getApplyNo, approveInfoDto.getApplyNo()).eq(ApplyOprRecord::getApplyType, String.valueOf(OrderOprType.RECONSIDER)));
        //审批记录表`
        WorkflowRecordDetails applyRecordDetails = new WorkflowRecordDetails();
        applyRecordDetails.setApproveDate(approveInfoDto.getOccurrenceTime());//时间
        applyRecordDetails.setApproveResult(approveInfoDto.getApproveType());//审批类型
        applyRecordDetails.setBusinessNo(approveInfoDto.getApplyNo());//申请编号
        applyRecordDetails.setApproveRemarks(approveInfoDto.getApproveType());//拒绝key
        if (AProveBusinessTypeEnum.BACK.getCode().equals(approveInfoDto.getApproveType())) {
            if (StringUtil.isNotEmpty(approveInfoDto.getStageId())) {
                applyRecordDetails.setProcessId(approveInfoDto.getStageId());
            }
            applyRecordDetails.setBusinessType(AProveBusinessTypeEnum.BACK.getCode());
        }
        //保存审批记录
        this.applyRecordDetailsService.save(applyRecordDetails);
        log.info("保存审批记录,{}", approveInfoDto.getApplyNo());
        log.info("======================更新操作记录表,{}====================", approveInfoDto.getApplyNo());
        //更新操作记录表
        ApplyOrderInfo applyOrderInfo = new ApplyOrderInfo();
        applyOrderInfo.setApplyNo(approveInfoDto.getApplyNo());
        if (AProveBusinessTypeEnum.PENDING_REVIEW.getCode().equals(approveInfoDto.getApproveType())) {
            //更新订单表状态,待审核->待审核
            log.info("-------状态待审核:" + AProveBusinessTypeEnum.PENDING_REVIEW.getCode() + "传值：" + approveInfoDto);
            applyOrderInfo.setApplyStatus(ApplyConstants.APPLY_STATUS_PENDING);
            //更新订单信息
            this.applyOrderInfoService.updateOrderApplyStatus(applyOrderInfo);
        } else if (AProveBusinessTypeEnum.AUDIT.getCode().equals(approveInfoDto.getApproveType())) {
            //更新订单表状态,审核中->审核中
            log.info("-------状态审核中:" + AProveBusinessTypeEnum.AUDIT.getCode() + "传值：" + approveInfoDto);
            applyOrderInfo.setApplyStatus(ApplyConstants.APPLY_STATUS_APPROVE);
            //更新订单信息
            this.applyOrderInfoService.updateOrderApplyStatus(applyOrderInfo);
        } else if (AProveBusinessTypeEnum.APPROVAL.getCode().equals(approveInfoDto.getApproveType())) {
            //更新订单表状态,核准->核准
            log.info("-------信审状态核准:" + AProveBusinessTypeEnum.APPROVAL.getCode() + "传值：" + approveInfoDto);
            applyOrderInfo.setApplyStatus(ApplyConstants.APPLY_STATUS_PASS);

            //正式复议-核准，更新复议操作记录
            if (approveInfoDto.getOccurrenceTime() == null) {
                applyOrderInfo.setRiskPassDate(new Date());
            }
            //信审核准，设置核准时间
            applyOrderInfo.setRiskPassDate(approveInfoDto.getOccurrenceTime());
            //更新订单信息
            this.applyOrderInfoService.updateOrderApplyStatus(applyOrderInfo);
            //新增合同信息
            ApplyContractInfo applyContractInfo = this.applyContractInfoService.getContractInfoByAppplyNo(approveInfoDto.getApplyNo());
            if (applyContractInfo == null) {
                this.newContractInfo(approveInfoDto);
            }
            //申请编号，合同号，状态，待提交
        } else if (AProveBusinessTypeEnum.REJECTION.getCode().equals(approveInfoDto.getApproveType())) {
            //更新订单表状态,拒绝->拒绝
            log.info("------状态拒绝:" + AProveBusinessTypeEnum.REJECTION.getCode() + "传值：" + approveInfoDto);
            applyOrderInfo.setApplyStatus(ApplyConstants.APPLY_STATUS_REFUSE);
            applyOrderInfo.setCancelDate(new Date());
            //更新订单信息
            this.applyOrderInfoService.updateOrderApplyStatus(applyOrderInfo);
            //订单拒绝,推送拒绝信息至归档(申请废弃)
            archiveMQService.archivePushMQ(String.valueOf(orderInfoByApplyNo.getId()), null, orderInfoByApplyNo.getApplyNo(), ArchiveConfig.wworder_refuse);
        } else if (AProveBusinessTypeEnum.CANCELLATION.getCode().equals(approveInfoDto.getApproveType())) {
            //更新订单状态,撤销
            log.info("------信审状态撤销:" + AProveBusinessTypeEnum.CANCELLATION.getCode() + "传值：" + approveInfoDto);
            applyOrderInfo.setApplyStatus(ApplyConstants.APPLY_STATUS_REVOKE);
            applyOrderInfo.setCancelDate(new Date());
            //更新订单信息
            this.applyOrderInfoService.updateOrderApplyStatus(applyOrderInfo);
            //订单拒绝,推送拒绝信息至归档(申请废弃)
            archiveMQService.archivePushMQ(String.valueOf(orderInfoByApplyNo.getId()), null, orderInfoByApplyNo.getApplyNo(), ArchiveConfig.wworder_refuse);
        } else if (AProveBusinessTypeEnum.BACK.getCode().equals(approveInfoDto.getApproveType())) {
            //更新订单状态，退回->修订暂停
            log.info("信审退回----->状态更新——->修订-暂停:" + AProveBusinessTypeEnum.BACK.getCode() + "传值：" + approveInfoDto + "----------流程id：" + approveInfoDto.getStageId());
            //复议退回/常规退回，都保存待办任务
            WorkflowAgencyTask workflowAgencyTask = new WorkflowAgencyTask();
            workflowAgencyTask.setBusinessNo(approveInfoDto.getApplyNo());
            workflowAgencyTask.setStatus(AProveBusinessTypeEnum.BACK.getCode());
            workflowAgencyTask.setProcessId(approveInfoDto.getStageId());
            workflowAgencyTask.setCustName(mainCustBaseInfo.getCustName());
            workflowAgencyTask.setCreateBy(mainCustBaseInfo.getCreateBy());
            workflowAgencyTask.setCreateTime(new Date());
            //存在复议操作记录-保存复议退回代办任务
            if (ObjectUtil.isNotNull(applyOprRecord)) {
                workflowAgencyTask.setBusinessType(String.valueOf(OrderOprType.RECONSIDER));
                //保存复议退回(修订暂停)留言
                this.saveRemindDetails(approveInfoDto, String.valueOf(OrderOprType.RECONSIDER));
                applyOprRecord.setApproveRemarks(approveInfoDto.getApproveReason());
                //更新订单信息
                this.applyOrderInfoService.updateOrderApplyStatus(applyOrderInfo);
                //更新操作记录表内得退回审批留言
                applyOprRecordService.updateById(applyOprRecord);
            } else {
                //不存在复议操作记录-保存常规退回代办任务记录
                workflowAgencyTask.setBusinessType(String.valueOf(OrderOprType.NORMAL));
                //保存常规退回(修订暂停)留言
                this.saveRemindDetails(approveInfoDto, null);
            }
            //保存退回代办任务
            this.workflowAgencyTaskService.save(workflowAgencyTask);
            log.info("保存退回审批代办任务记录:{}", workflowAgencyTask.getBusinessType());
            //更新订单状态-修订暂停
            applyOrderInfo.setApplyStatus(ApplyConstants.APPLY_STATUS_SUSPEND);
            //更新订单信息
            this.applyOrderInfoService.updateOrderApplyStatus(applyOrderInfo);
            //更新客户申请主表玄武查询标记
            applyCustBaseInfoService.update(Wrappers.<ApplyCustBaseInfo>lambdaUpdate()
                    .eq(ApplyCustBaseInfo::getApplyNo, approveInfoDto.getApplyNo())
                    .set(ApplyCustBaseInfo::getRiskQueriedFlag, Boolean.TRUE));
        }
    }

    /**
     * 保存修订暂停留言(复议/常规)
     */
    public void saveRemindDetails(ApproveInformDto approveInfoDto, String businessType) {
        ApplyRemindDetails applyRemindDetails = new ApplyRemindDetails();
        if (StringUtil.isNotEmpty(businessType)) {
            //保存复议修订暂停业务类型
            applyRemindDetails.setBusinessType(businessType);
        }
        //保存常规修订暂停留言,无业务类型
        applyRemindDetails.setApplyNo(approveInfoDto.getApplyNo());
        applyRemindDetails.setMsgContent(approveInfoDto.getApproveReason());
        applyRemindDetails.setIsSelf(WhetherEnum.No.getIndex());
        applyRemindDetails.setRemindType(approveInfoDto.getApproveType());
        applyRemindDetails.setCreateBy("审批专员");
        applyRemindDetails.setCreateTime(approveInfoDto.getOccurrenceTime());
        this.applyRemindDetailsService.save(applyRemindDetails);
    }

    /**
     * 订单核准后，新增合同信息
     *
     * @param approveInfoDto
     */
    public void newContractInfo(ApproveInformDto approveInfoDto) {
        //在合同表内插入一条数据
        ApplyContractInfo applyContractInfo = new ApplyContractInfo();
        applyContractInfo.setApplyNo(approveInfoDto.getApplyNo());
        applyContractInfo.setContractNo(approveInfoDto.getApplyNo() + "-001");
        applyContractInfo.setContractStatus(ApplyConstants.CONTRACT_STATUS_01);
        applyContractInfo.setCreateTime(new Date());
        applyContractInfo.setCreateBy("");
        this.applyContractInfoService.save(applyContractInfo);
        this.applyContractInfoService.update(Wrappers.<ApplyContractInfo>lambdaUpdate().set(ApplyContractInfo::getCreateBy, null).eq(ApplyContractInfo::getId, applyContractInfo.getId()));
    }

    /**
     * 解析留言通知报文,保存数据
     *
     * @param leaveMessageDto
     */
    @Transactional(rollbackFor = Exception.class)
    public void applyRemindDetails(LeaveMessageDto leaveMessageDto) {
        ApplyRemindDetails applyRemindDetails = new ApplyRemindDetails();
        if (ObjectUtil.isNotNull(leaveMessageDto)) {
            //如果留言不为空,判断是否存在留言类型，不存在，则是人工识别返回消息
            if (StringUtil.isEmpty(leaveMessageDto.getMessageType())) {
                //人工识别消息返回,判断是退回还是其他消息
                if (AProveBusinessTypeEnum.BACK.getCode().equals(leaveMessageDto.getMessageInfo())) {
                    //识别退回，更新订单为草稿
                    ApplyOrderInfo orderInfoByApplyNo = this.applyOrderInfoService.getOrderInfoByApplyNo(leaveMessageDto.getApplyNo());
                    orderInfoByApplyNo.setApplyStatus(ApplyConstants.APPLY_STATUS_DRAFT);
                    this.applyOrderInfoService.updateById(orderInfoByApplyNo);
                    log.info("經銷商识别退回:{}", leaveMessageDto.getApplyNo());
                    //保存留言信息
                    this.saveRemind(leaveMessageDto);
                }
            } else if (AProveBusinessTypeEnum.SEND_BACK_TO_DEALER.getCode().equals(leaveMessageDto.getMessageType())) {
                //人工确认签名队列退回,訂單變更爲草稿狀態--退回经销商
                this.applyOrderInfoService.updateApplyStatus(leaveMessageDto.getApplyNo(), ApplyConstants.APPLY_STATUS_DRAFT);
                //保存留言信息
                this.saveRemind(leaveMessageDto);
                log.info("流程外訂單退回:{},訂單退回草稿狀態", leaveMessageDto.getApplyNo());
            } else if (AProveBusinessTypeEnum.SUGGEST_REJECT_FINAL.getCode().equals(leaveMessageDto.getMessageType())) {
                //玄武资质不足-拒绝
                applyOrderInfoService.updateApplyStatus(leaveMessageDto.getApplyNo(), ApplyConstants.APPLY_STATUS_REFUSE);
                this.saveRemind(leaveMessageDto);
                log.info("{},资质不足-拒绝", leaveMessageDto.getApplyNo());
            } else {
                applyRemindDetails.setApplyNo(leaveMessageDto.getApplyNo());
                applyRemindDetails.setMsgContent(leaveMessageDto.getMessageInfo());
                applyRemindDetails.setRemindType(leaveMessageDto.getMessageType());
                applyRemindDetails.setIsReturn(leaveMessageDto.getIsRturn());
                applyRemindDetails.setCreateTime(leaveMessageDto.getMessageTime());
                applyRemindDetails.setMessageReason(leaveMessageDto.getMessageReason());
                applyRemindDetails.setIsSelf(WhetherEnum.No.getIndex());
            }

        }
    }

    /**
     * 保存留言信息
     *
     * @param leaveMessageDto
     */
    public void saveRemind(LeaveMessageDto leaveMessageDto) {
        ApplyRemindDetails applyRemindDetails = new ApplyRemindDetails();
        if (StringUtil.isNotEmpty(leaveMessageDto.getFlowType())) {
            if (WhetherEnum.YES.getIndex().equals(leaveMessageDto.getFlowType())) {
                applyRemindDetails.setBusinessType(String.valueOf(OrderOprType.RECONSIDER));
            }
        }
        //保存留言信息
        applyRemindDetails.setApplyNo(leaveMessageDto.getApplyNo());
        applyRemindDetails.setMsgContent(leaveMessageDto.getMessageInfo());
        applyRemindDetails.setRemindType(leaveMessageDto.getMessageType());
        applyRemindDetails.setIsReturn(WhetherEnum.No.getIndex());
        applyRemindDetails.setCreateTime(leaveMessageDto.getMessageTime());
        applyRemindDetails.setCreateBy("审批人员");
        applyRemindDetails.setMessageReason(leaveMessageDto.getMessageReason());
        applyRemindDetails.setIsSelf(WhetherEnum.No.getIndex());
        //保存留言
        this.applyRemindDetailsService.save(applyRemindDetails);
    }

    /**
     * 附条件核准报文解析，保存数据
     *
     * @param conditionalApptovalDto
     */
    public void applyConditionApptoval(ConditionalApprovalDto conditionalApptovalDto) {
        if (ObjectUtil.isNotNull(conditionalApptovalDto)) {
            //查询操作记录-复议
            ApplyOprRecord applyOprRecord = this.applyOprRecordService.getOne(Wrappers.<ApplyOprRecord>query().lambda().eq(ApplyOprRecord::getApplyNo, conditionalApptovalDto.getApplyNo())
                    .eq(ApplyOprRecord::getApplyType, String.valueOf(OrderOprType.RECONSIDER)));
            //更新复议操作记录状态为附条件核准
            if (ObjectUtil.isNotNull(applyOprRecord)) {
                applyOprRecord.setApplyStatus(FormalReviewEnums.FORMALRECONDITIONALAPPROVAL.getCode());
                this.applyOprRecordService.updateById(applyOprRecord);
            }
            String applyNo = conditionalApptovalDto.getApplyNo();
            JSONObject jsonObject = JSONObject.parseObject(conditionalApptovalDto.getConditionalApproval());
            JSONArray finCarDetailsList = jsonObject.getJSONArray("finCarDetailsList");
            JSONArray finCostDetailsList = jsonObject.getJSONArray("finCostDetailsList");
            JSONArray finCarStyleDetailList = jsonObject.getJSONArray("finCarStyleDetailList");
            JSONArray finFinancingItemsList = jsonObject.getJSONArray("finFinancingItemsList");
            log.info("jsonObject:{}", jsonObject);
            log.info("finCostDetailsList:{}", finCostDetailsList);
            log.info("finCarStyleDetailList:{}", finCarStyleDetailList);
            log.info("finFinancingItemsList:{}", finFinancingItemsList);
            //保存审批记录
            WorkflowRecordDetails recordDetails = new WorkflowRecordDetails();
            recordDetails.setBusinessNo(applyNo);
            recordDetails.setBusinessType(AProveBusinessTypeEnum.SUGGEST_CONDITION_FINAL.getCode());
            recordDetails.setApproveDesc(conditionalApptovalDto.getConditionalReason());
            //保存信审传来的附条件准参数
            ApplyConditionApproval applyConditionApproval = new ApplyConditionApproval();
            applyConditionApproval.setApplyNo(applyNo);
            //核准前参数
            applyConditionApproval.setApproveContent(jsonObject.toJSONString());
            applyConditionApproval.setCreateTime(new Date());
            //保存
            applyConditionApprovalService.save(applyConditionApproval);
            applyRecordDetailsService.save(recordDetails);
            this.applyOrderInfoService.updateApplyStatus(applyNo, ApplyConstants.APPLY_STATUS_CONDITION);
            log.info("{}-信审附条件核准信息保存完成", applyNo);
        }
    }


    /**
     * 解析审批记录报文,保存数据,更新合同表的合同状态
     *
     * @param backToPartnersDTO
     */
    public void applyBackToPartner(SendToApplyContractInfoDTO backToPartnersDTO) {
        if (ObjectUtils.isEmpty(backToPartnersDTO)) {
            throw new RuntimeException("合同编号:" + backToPartnersDTO.getContractNo() + ",backToPartnersDTO不能为空");
        } else if (ObjectUtils.isEmpty(backToPartnersDTO.getContractNo())) {
            throw new RuntimeException("合同编号:" + backToPartnersDTO.getContractNo() + ",审批,合同编号不能为空");
        }
        log.info("-------放款/GPS审核数据:-------" + backToPartnersDTO);
        ApplyContractInfo applyContractInfo = applyContractInfoService.getOne(Wrappers.<ApplyContractInfo>query().lambda().eq(ApplyContractInfo::getContractNo, backToPartnersDTO.getContractNo()));
        //审批记录表
        WorkflowRecordDetails applyRecordDetails = new WorkflowRecordDetails();
        //合同编号
        applyRecordDetails.setBusinessNo(backToPartnersDTO.getContractNo());
        //操作时间
        applyRecordDetails.setApproveDate(backToPartnersDTO.getOperateTime());
        //流程id
        applyRecordDetails.setProcessId(backToPartnersDTO.getStageId());
        //审批建议
        if (backToPartnersDTO.getStatus() == null) {
            applyRecordDetails.setBusinessType(ApplyConstants.LOAN_APPROVAL);
            if (ApplyStatusEnum.LOAN_RETURN.getState().equals(backToPartnersDTO.getApproveType())) {
                log.info("-------放款退件:" + ApplyStatusEnum.LOAN_RETURN);
                applyRecordDetails.setApproveResult(backToPartnersDTO.getApproveType());
                this.applyRecordDetailsService.save(applyRecordDetails);
                applyContractInfo.setContractStatus(ApplyConstants.CONTRACT_STATUS_BACK);
                applyContractInfoService.updateById(applyContractInfo);
            } else if (ApplyStatusEnum.LOAN_PRE_APPROVE.getState().equals(backToPartnersDTO.getApproveType())) {
                //放款通过日期，修改合同状态通过
                applyRecordDetails.setApproveResult(backToPartnersDTO.getApproveType());
                this.applyRecordDetailsService.save(applyRecordDetails);
                log.info("----放款通过----" + ApplyStatusEnum.LOAN_PRE_APPROVE);
                applyContractInfo.setLendingPassDate(backToPartnersDTO.getOperateTime());
                applyContractInfo.setContractStatus(ApplyConstants.CONTRACT_STATUS_PASS);
                applyContractInfoService.updateById(applyContractInfo);
            } else if (ApplyStatusEnum.LOAN_DISCARD.getState().equals(backToPartnersDTO.getApproveType())) {
                applyRecordDetails.setApproveResult(backToPartnersDTO.getApproveType());
                this.applyRecordDetailsService.save(applyRecordDetails);
                log.info("----放款取消----" + ApplyStatusEnum.LOAN_DISCARD);
                applyContractInfo.setContractStatus(ApplyConstants.CONTRACT_STATUS_CANCEL);
                applyContractInfoService.updateById(applyContractInfo);
                ApplyOrderInfo applyOrderInfo=orderInfoService.getOrderInfoByApplyNo(applyContractInfo.getApplyNo());
                applyOrderInfo.setCancelDate(new Date());
                applyOrderInfo.setApplyStatus(ApplyConstants.APPLY_STATUS_CANCEL);
                orderInfoService.updateById(applyOrderInfo);
                archiveMQService.archivePushMQ(applyContractInfo.getId().toString(), applyContractInfo.getContractNo(), applyContractInfo.getApplyNo(), ArchiveConfig.wwcontract_cancel);
            } else if (ApplyStatusEnum.LOAN_APPROVE_DONE.getState().equals(backToPartnersDTO.getApproveType())) {
                applyContractInfo.setLendingPassDate(new Date());
                applyContractInfoService.updateById(applyContractInfo);
                if (backToPartnersDTO.getAttachmentDtoList().size() > 0) {
                    for (AttachmentDTO attachmentDTO : backToPartnersDTO.getAttachmentDtoList()) {
                        ComAttachmentFile attachmentFile = new ComAttachmentFile();
                        BeanUtils.copyProperties(attachmentDTO, attachmentFile);
                        this.comAttachmentFileService.updateById(attachmentFile);
                    }
                }
                archiveMQService.archivePushMQ(applyContractInfo.getId().toString(), applyContractInfo.getContractNo(), applyContractInfo.getApplyNo(), ArchiveConfig.wwcontract_approved);
            } else {
                applyRecordDetails.setApproveResult(backToPartnersDTO.getApproveType());
                this.applyRecordDetailsService.save(applyRecordDetails);
                log.info("----放款审核中----" + backToPartnersDTO.getApproveType());
                applyContractInfo.setContractStatus(ApplyConstants.CONTRACT_STATUS_APPROVE);
                applyContractInfoService.updateById(applyContractInfo);
            }
            //放款操作记录表
            if (backToPartnersDTO.getBackMsgDtoList() != null) {
                List<String> fileTypeList = new ArrayList<>();
                for (int i = 0; i < backToPartnersDTO.getBackMsgDtoList().size(); i++) {
                    ApplyReturnRecord applyReturnRecord = new ApplyReturnRecord();
                    applyReturnRecord.setApplyNo(applyContractInfo.getApplyNo());
                    applyReturnRecord.setContractNo(backToPartnersDTO.getContractNo());
                    applyReturnRecord.setRecordId(applyRecordDetails.getId());
                    applyReturnRecord.setReturnType(backToPartnersDTO.getBackMsgDtoList().get(i).getFileType());
                    applyReturnRecord.setProblemDesc(backToPartnersDTO.getBackMsgDtoList().get(i).getBackDesc());
                    applyReturnRecord.setBackWords(backToPartnersDTO.getBackMsgDtoList().get(i).getBackWords());
                    applyReturnRecord.setTaskId(backToPartnersDTO.getTaskId());
                    fileTypeList.add(backToPartnersDTO.getBackMsgDtoList().get(i).getFileType());
                    this.applyReturnRecordService.save(applyReturnRecord);
                }
//                this.comAttachmentFileService.updateFileStatusForLoan(backToPartnersDTO.getContractNo(), fileTypeList);
                if (backToPartnersDTO.getAttachmentDtoList().size() > 0) {
                    for (AttachmentDTO attachmentDTO : backToPartnersDTO.getAttachmentDtoList()) {
                        ComAttachmentFile attachmentFile = new ComAttachmentFile();
                        BeanUtils.copyProperties(attachmentDTO, attachmentFile);
                        this.comAttachmentFileService.updateById(attachmentFile);
                    }
                }
                log.info("文件类型落库{}", fileTypeList);
            }
        } else {
            log.info("-------GPS审核backToPartnersDTO:" + backToPartnersDTO.getStatus());
            applyRecordDetails.setBusinessType(ApplyConstants.GPS_APPROVAL);
            applyRecordDetails.setApproveResult(backToPartnersDTO.getStatus());
            this.applyRecordDetailsService.save(applyRecordDetails);
            applyContractInfo.setGpsStatus(backToPartnersDTO.getStatus());
            applyContractInfoService.updateById(applyContractInfo);
        }
    }


    /**
     * GPS规则配置表数据
     **/
    @Transactional(rollbackFor = Exception.class)
    public void applyLoanGpsRuleInfo(LoanGpsRuleDTO loanGpsRuleDTO) {
        if (ObjectUtils.isEmpty(loanGpsRuleDTO.getLoanGpsRuleInfoDTO())) {
            throw new RuntimeException("***************GPS规则数据不能为空***************");
        }
        LoanGpsRuleInfo loanGpsRuleInfo = new LoanGpsRuleInfo();
        BeanUtils.copyProperties(loanGpsRuleDTO.getLoanGpsRuleInfoDTO(), loanGpsRuleInfo);
        loanGpsRuleInfo.setInstallType(loanGpsRuleInfo.getGpsRuleName());
        if (ObjectUtil.isNotNull(loanGpsRuleInfo)) {
            LoanGpsRuleInfo loanGpsRuleInfo1 = this.loanGpsRuleInfoMapper.selectById(loanGpsRuleInfo);
            if (ObjectUtil.isNotNull(loanGpsRuleInfo1)) {
                this.loanGpsRuleInfoMapper.updateById(loanGpsRuleInfo);
            } else {
                this.loanGpsRuleInfoMapper.insert(loanGpsRuleInfo);
            }
        }
        //规则信息
        AfsRuleInfoDto afsRuleInfoDto = loanGpsRuleDTO.getAfsRuleInfoDto();
        if (ObjectUtil.isNotNull(afsRuleInfoDto)) {
            List<AfsRuleInfo> oldRuleInfo = afsRuleInfoService.list(Wrappers.<AfsRuleInfo>query().lambda().eq(AfsRuleInfo::getRuleNo, afsRuleInfoDto.getRuleNo()));
            if (ObjectUtil.isNotNull(oldRuleInfo)) {
                for (AfsRuleInfo afsRuleInfo : oldRuleInfo) {
                    afsRuleInfoService.deActiveRule(afsRuleInfo.getId());
                }
            }
            AfsRuleInfo afsRuleInfo = new AfsRuleInfo();
            BeanUtils.copyProperties(afsRuleInfoDto, afsRuleInfo);
            afsRuleInfoService.save(afsRuleInfo);
        }
        //规则转换为可执行表达式记录
        List<AfsRuleTransExpress> transExpressList = loanGpsRuleDTO.getAfsRuleTransExpress();
        if (CollectionUtil.isNotEmpty(transExpressList)) {
            for (AfsRuleTransExpress afsRuleTransExpress : transExpressList) {
                AfsRuleTransExpress ruleTransExpress = this.ruleTransExpressMapper.selectById(afsRuleTransExpress);
                if (ObjectUtil.isNotNull(ruleTransExpress)) {
                    this.ruleTransExpressMapper.updateById(afsRuleTransExpress);
                } else {
                    this.ruleTransExpressMapper.insert(afsRuleTransExpress);
                }
            }
        }
        //规则输出映射表
        AfsRuleResultMapping afsRuleResultMapping = new AfsRuleResultMapping();
        AfsRuleResultMapping afsRuleResultMapping1 = loanGpsRuleDTO.getAfsRuleResultMapping();
        if (afsRuleResultMapping1 != null) {
            BeanUtils.copyProperties(afsRuleResultMapping1, afsRuleResultMapping);
            if (ObjectUtil.isNotNull(afsRuleResultMapping)) {
                AfsRuleResultMapping ruleResultMapping = this.afsRuleResultMappingMapper.selectById(afsRuleResultMapping);
                if (ObjectUtil.isNotNull(ruleResultMapping)) {
                    this.afsRuleResultMappingMapper.updateById(afsRuleResultMapping);
                } else {
                    this.afsRuleResultMappingMapper.insert(afsRuleResultMapping);
                }
            }
        }
        //规则配置项信息
        List<AfsRuleItem> afsRuleItemList = loanGpsRuleDTO.getAfsRuleItem();
        if (CollectionUtil.isNotEmpty(afsRuleItemList)) {
            for (AfsRuleItem afsRuleItem : afsRuleItemList) {
                AfsRuleItem afsRule = this.ruleItemMapper.selectById(afsRuleItem);
                if (ObjectUtil.isNotNull(afsRule)) {
                    this.ruleItemMapper.updateById(afsRuleItem);
                } else {
                    this.ruleItemMapper.insert(afsRuleItem);
                }
            }
        }
        //规则原子映射配置表
        List<AfsRuleInputMapping> afsRuleInputMappingList = loanGpsRuleDTO.getAfsRuleInputMapping();
        if (CollectionUtil.isNotEmpty(afsRuleInputMappingList)) {
            for (AfsRuleInputMapping afsRuleInputMapping : afsRuleInputMappingList) {
                AfsRuleInputMapping afsRuleInput = this.mappingMapper.selectById(afsRuleInputMapping);
                if (ObjectUtil.isNotNull(afsRuleInput)) {
                    this.mappingMapper.updateById(afsRuleInputMapping);
                } else {
                    this.mappingMapper.insert(afsRuleInputMapping);
                }
            }
        }
        //三元表达式左右原子信息
        List<AfsRuleExpressAtom> afsRuleExpressAtomList = loanGpsRuleDTO.getAfsRuleExpressAtom();
        if (CollectionUtil.isNotEmpty(afsRuleExpressAtomList)) {
            for (AfsRuleExpressAtom afsRuleExpressAtom : afsRuleExpressAtomList) {
                AfsRuleExpressAtom afsRuleExpress = this.ruleExpressAtomMapper.selectById(afsRuleExpressAtom.getId());
                if (ObjectUtil.isNotNull(afsRuleExpress)) {
                    this.ruleExpressAtomMapper.updateById(afsRuleExpressAtom);
                } else {
                    this.ruleExpressAtomMapper.insert(afsRuleExpressAtom);
                }
            }
        }
        //配置项三元表达式信息
        List<AfsRuleExpress> afsRuleExpressList = loanGpsRuleDTO.getAfsRuleExpress();
        if (CollectionUtil.isNotEmpty(afsRuleExpressList)) {
            for (AfsRuleExpress afsRuleExpress : afsRuleExpressList) {
                AfsRuleExpress afsRuleExpress1 = this.ruleExpressMapper.selectById(afsRuleExpress.getId());
                if (ObjectUtil.isNotNull(afsRuleExpress1)) {
                    this.ruleExpressMapper.updateById(afsRuleExpress);
                } else {
                    this.ruleExpressMapper.insert(afsRuleExpress);
                }
            }
        }
    }

    /**
     * 放款模式规则配置表数据
     **/
    @Transactional(rollbackFor = Exception.class)
    public void applyLoanModelRuleInfo(LoanModelRuleDto loanModelRuleDto) {
        if (ObjectUtils.isEmpty(loanModelRuleDto.getLoanModelRuleInfoDto())) {
            throw new RuntimeException("***************放款模式规则数据不能为空***************");
        }
        LoanModeRuleInfo loanModeRuleInfo = new LoanModeRuleInfo();
        BeanUtils.copyProperties(loanModelRuleDto.getLoanModelRuleInfoDto(), loanModeRuleInfo);
        if (ObjectUtil.isNotNull(loanModeRuleInfo)) {
            LoanModeRuleInfo loanModeRuleInfo1 = this.loanModeRuleInfoMapper.selectById(loanModeRuleInfo);
            if (ObjectUtil.isNotNull(loanModeRuleInfo1)) {
                this.loanModeRuleInfoMapper.updateById(loanModeRuleInfo);
            } else {
                this.loanModeRuleInfoMapper.insert(loanModeRuleInfo);
            }
        }
        //规则信息
        AfsRuleInfoDto afsRuleInfoDto = loanModelRuleDto.getAfsRuleInfoDto();
        if (ObjectUtil.isNotNull(afsRuleInfoDto)) {
            List<AfsRuleInfo> oldRuleInfo = afsRuleInfoService.list(Wrappers.<AfsRuleInfo>query().lambda().eq(AfsRuleInfo::getRuleNo, afsRuleInfoDto.getRuleNo()));
            if (ObjectUtil.isNotNull(oldRuleInfo)) {
                for (AfsRuleInfo afsRuleInfo : oldRuleInfo) {
                    afsRuleInfoService.deActiveRule(afsRuleInfo.getId());
                }
            }
            AfsRuleInfo afsRuleInfo = new AfsRuleInfo();
            BeanUtils.copyProperties(afsRuleInfoDto, afsRuleInfo);
            afsRuleInfoService.save(afsRuleInfo);
        }
        //规则转换为可执行表达式记录
        List<AfsRuleTransExpress> transExpressList = loanModelRuleDto.getAfsRuleTransExpress();
        if (CollectionUtil.isNotEmpty(transExpressList)) {
            for (AfsRuleTransExpress afsRuleTransExpress : transExpressList) {
                AfsRuleTransExpress ruleTransExpress = this.ruleTransExpressMapper.selectById(afsRuleTransExpress);
                if (ObjectUtil.isNotNull(ruleTransExpress)) {
                    this.ruleTransExpressMapper.updateById(afsRuleTransExpress);
                } else {
                    this.ruleTransExpressMapper.insert(afsRuleTransExpress);
                }
            }
        }
        //规则输出映射表
        AfsRuleResultMapping afsRuleResultMapping = new AfsRuleResultMapping();
        AfsRuleResultMapping afsRuleResultMapping1 = loanModelRuleDto.getAfsRuleResultMapping();
        if (afsRuleResultMapping1 != null) {
            BeanUtils.copyProperties(afsRuleResultMapping1, afsRuleResultMapping);
            if (ObjectUtil.isNotNull(afsRuleResultMapping)) {
                AfsRuleResultMapping ruleResultMapping = this.afsRuleResultMappingMapper.selectById(afsRuleResultMapping);
                if (ObjectUtil.isNotNull(ruleResultMapping)) {
                    this.afsRuleResultMappingMapper.updateById(afsRuleResultMapping);
                } else {
                    this.afsRuleResultMappingMapper.insert(afsRuleResultMapping);
                }
            }
        }
        //规则配置项信息
        List<AfsRuleItem> afsRuleItemList = loanModelRuleDto.getAfsRuleItem();
        if (CollectionUtil.isNotEmpty(afsRuleItemList)) {
            for (AfsRuleItem afsRuleItem : afsRuleItemList) {
                AfsRuleItem afsRule = this.ruleItemMapper.selectById(afsRuleItem);
                if (ObjectUtil.isNotNull(afsRule)) {
                    this.ruleItemMapper.updateById(afsRuleItem);
                } else {
                    this.ruleItemMapper.insert(afsRuleItem);
                }
            }
        }
        //规则原子映射配置表
        List<AfsRuleInputMapping> afsRuleInputMappingList = loanModelRuleDto.getAfsRuleInputMapping();
        if (CollectionUtil.isNotEmpty(afsRuleInputMappingList)) {
            for (AfsRuleInputMapping afsRuleInputMapping : afsRuleInputMappingList) {
                AfsRuleInputMapping afsRuleInput = this.mappingMapper.selectById(afsRuleInputMapping);
                if (ObjectUtil.isNotNull(afsRuleInput)) {
                    this.mappingMapper.updateById(afsRuleInputMapping);
                } else {
                    this.mappingMapper.insert(afsRuleInputMapping);
                }
            }
        }
        //三元表达式左右原子信息
        List<AfsRuleExpressAtom> afsRuleExpressAtomList = loanModelRuleDto.getAfsRuleExpressAtom();
        if (CollectionUtil.isNotEmpty(afsRuleExpressAtomList)) {
            for (AfsRuleExpressAtom afsRuleExpressAtom : afsRuleExpressAtomList) {
                AfsRuleExpressAtom afsRuleExpress = this.ruleExpressAtomMapper.selectById(afsRuleExpressAtom.getId());
                if (ObjectUtil.isNotNull(afsRuleExpress)) {
                    this.ruleExpressAtomMapper.updateById(afsRuleExpressAtom);
                } else {
                    this.ruleExpressAtomMapper.insert(afsRuleExpressAtom);
                }
            }
        }
        //配置项三元表达式信息
        List<AfsRuleExpress> afsRuleExpressList = loanModelRuleDto.getAfsRuleExpress();
        if (CollectionUtil.isNotEmpty(afsRuleExpressList)) {
            for (AfsRuleExpress afsRuleExpress : afsRuleExpressList) {
                AfsRuleExpress afsRuleExpress1 = this.ruleExpressMapper.selectById(afsRuleExpress.getId());
                if (ObjectUtil.isNotNull(afsRuleExpress1)) {
                    this.ruleExpressMapper.updateById(afsRuleExpress);
                } else {
                    this.ruleExpressMapper.insert(afsRuleExpress);
                }
            }
        }
    }


    /**
     * 批量取消放款申请
     *
     * @param applyNoList
     */
    public void applyLoanCancel(String applyNoList) {
        String[] arr = applyNoList.split(",");
        for (int i = 0; i < arr.length; i++) {
            ApplyContractInfo applyContractInfo = applyContractInfoService.getContractInfoByAppplyNo(arr[i]);
            applyContractInfo.setContractStatus(ApplyConstants.CONTRACT_STATUS_CANCEL);
            applyContractInfo.setCancelDate(new Date());
            applyContractInfoService.updateById(applyContractInfo);
            ApplyOrderInfo applyOrderInfo=orderInfoService.getOrderInfoByApplyNo(applyContractInfo.getApplyNo());
            applyOrderInfo.setCancelDate(new Date());
            applyOrderInfo.setApplyStatus(ApplyConstants.APPLY_STATUS_CANCEL);
            orderInfoService.updateById(applyOrderInfo);
            archiveMQService.archivePushMQ(applyContractInfo.getId().toString(), applyContractInfo.getContractNo(), applyContractInfo.getApplyNo(), ArchiveConfig.wwcontract_discard);
        }
    }
}